package com.cykj.pos.service.Impl;

import com.cykj.common.utils.StringUtils;
import com.cykj.pos.domain.BizTransactionAmountEntity;
import com.cykj.pos.domain.BizTransactionStatisticsRecord;
import com.cykj.pos.domain.TransactionEntity;
import com.cykj.pos.domain.test;
import com.cykj.pos.domain.BizMerchParentRelateds;
import com.cykj.pos.mapper.TransactionMapper;
import com.cykj.pos.service.TransactionService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author SunJinDuo
 * @date 2022/7/19
 */
@Service
public class TransactionServiceImpl implements TransactionService {

    private static final Logger logger = LoggerFactory.getLogger(TransactionServiceImpl.class);

    @Autowired
    private TransactionMapper transactionMapper;

    /**
     * @author: haoran
     * @date: 2022/8/18
     * 方法名称： 测试
     */
    @Override
    @Transactional
    public void test() {
        List<test> list = transactionMapper.test();
//        test list = transactionMapper.test();
        System.out.println("//////" + list.size());
        String a = "";
        String b = "";
        String c = "";
        String d = "";
        for (test t : list) {
            a = t.getHostDate().substring(0, 10);
            System.out.println("+++" + a);
            b = t.getHostDate().substring(12);
            System.out.println("+++" + b);
            c = a + " " + b;
            System.out.println("+++" + c);
            test qwe = new test();
            qwe.setId(t.getId());
            qwe.setHostDate(c);
            transactionMapper.update(qwe);
        }
    }

    @Override
    public void statistic(Long transactionAmountId) throws ParseException {
        //        logger.info("<<<<<--- 实现方法开始时间：" + startTime + " --->>>>> -");
        //用于存储变化数据map
        Map<String, BizTransactionStatisticsRecord> map = new HashMap<String, BizTransactionStatisticsRecord>();
        BizTransactionStatisticsRecord btsr = null;
        // 查询平台化交易通知队列表中的数据
//        logger.info("<<<<<--- 开始查询平台化交易通知队列表中的数据 --->>>>> -");
        List<TransactionEntity> list = transactionMapper.statistics(transactionAmountId);
//        logger.info("<<<<<--- 查询完平台化交易通知队列表中的数据：" + list + " --->>>>> -");
        // 往map内放值
//        logger.info("<<<<<--- 调用往map内放值方法 --->>>>> -");
        map = this.putMap(btsr, list);
        // 处理数据库数据
//        logger.info("<<<<<--- 调用处理数据库数据方法 --->>>>> -");
        this.processingData(map, btsr);
        // 删除队列：已处理完的数据
//        if (list.size() > 0) {
////            logger.info("<<<<<--- 删除队列：已处理完的数据 --->>>>> -");
//            TransactionEntity transactionEntity = list.remove(list.size() - 1);
//            transactionMapper.delete(transactionEntity.getId());
////            logger.info("<<<<<--- 删除队列完毕 --->>>>> -");
//        }
        for(TransactionEntity transactionEntity:list){
            transactionMapper.delete(transactionEntity.getId());
        }
//        String endTime = df.format(System.currentTimeMillis());
//        logger.info("<<<<<--- 实现方法结束时间：" + endTime + " --->>>>> -");
    }

    /**
     * @author: haoran
     * @date: 2022/7/19
     * 方法名称： 流水统计（预计算）
     */
    @Override
    @Transactional
    public void statistics() throws ParseException {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String startTime = df.format(System.currentTimeMillis());
//        logger.info("<<<<<--- 实现方法开始时间：" + startTime + " --->>>>> -");
        //用于存储变化数据map
        Map<String, BizTransactionStatisticsRecord> map = new HashMap<String, BizTransactionStatisticsRecord>();
        BizTransactionStatisticsRecord btsr = null;
        // 查询平台化交易通知队列表中的数据
//        logger.info("<<<<<--- 开始查询平台化交易通知队列表中的数据 --->>>>> -");
        List<TransactionEntity> list = transactionMapper.statistics(null);
//        logger.info("<<<<<--- 查询完平台化交易通知队列表中的数据：" + list + " --->>>>> -");
        // 往map内放值
//        logger.info("<<<<<--- 调用往map内放值方法 --->>>>> -");
        map = this.putMap(btsr, list);
        // 处理数据库数据
//        logger.info("<<<<<--- 调用处理数据库数据方法 --->>>>> -");
        this.processingData(map, btsr);
//        // 删除队列：已处理完的数据
//        if (list.size() > 0) {
////            logger.info("<<<<<--- 删除队列：已处理完的数据 --->>>>> -");
//            TransactionEntity transactionEntity = list.remove(list.size() - 1);
//            transactionMapper.delete(transactionEntity.getId());
////            logger.info("<<<<<--- 删除队列完毕 --->>>>> -");
//        }

        for(TransactionEntity transactionEntity:list){
            transactionMapper.delete(transactionEntity.getId());
        }
//        String endTime = df.format(System.currentTimeMillis());
//        logger.info("<<<<<--- 实现方法结束时间：" + endTime + " --->>>>> -");
    }

    /**
     * @author: haoran
     * @date: 2022/7/21
     * 方法名称： 往map内放值
     */
    public Map<String, BizTransactionStatisticsRecord> putMap(BizTransactionStatisticsRecord btsr, List<TransactionEntity> list) {
//        logger.info("<<<<<--- 往map内放值，接收到的List为：" + list + " --->>>>> -");
        Map<String, BizTransactionStatisticsRecord> map = new HashMap<String, BizTransactionStatisticsRecord>();
        for (TransactionEntity transactionEntity : list) {
            btsr = new BizTransactionStatisticsRecord();
            // 通过交易通知表id查询该id的所有数据
//            logger.info("<<<<<--- 通过交易通知表id查询该id的所有数据，本次的id为：" + transactionEntity.getTransactionAmountId() + " --->>>>> -");
            BizTransactionAmountEntity bizTransactionAmountEntity = transactionMapper.selectAll(transactionEntity.getTransactionAmountId());
//            if(bizTransactionAmountEntity.getWhetherSteal()==1){
//                continue;
//            }
            if(bizTransactionAmountEntity==null){
                continue;
            }else if (bizTransactionAmountEntity.getMerchId()==null||bizTransactionAmountEntity.getMerchId()==0){
                continue;
            }
//            logger.info("<<<<<--- 当id为：" + transactionEntity.getTransactionAmountId() + "。的时候查出来的数据为：" + bizTransactionAmountEntity + " --->>>>> -");
            // 判断该处理流水是否会对重置任务造成影响，如有影响流水重新如队列
//            logger.info("<<<<<--- 判断merchId为：" + bizTransactionAmountEntity.getMerchId() + "时，该处理流水是否会对重置任务造成影响，如有影响，流水重新入队列 --->>>>> -");
            int a = transactionMapper.selectReset(bizTransactionAmountEntity.getMerchId());
            if(a != 0){
                transactionMapper.delete(transactionEntity.getId());
                transactionEntity.setId(null);
                transactionMapper.insertTr(transactionEntity);
//                logger.info("<<<<<--- merchId为：" + bizTransactionAmountEntity.getMerchId() + "的数据已经重新入完队列，跳出本次循环 --->>>>> -");
                continue;
            }
//            logger.info("<<<<<--- merchId为：" + bizTransactionAmountEntity.getMerchId() + "时，该处理流水对没有对重置任务造成影响 --->>>>> -");
            // 查询当前用户所在的表的后缀
            String suffix = transactionMapper.selectSuffix(bizTransactionAmountEntity.getMerchId());
            if(StringUtils.isBlank(suffix)){
                continue;
            }
            String tableName = "biz_transaction_amount_" + suffix;
//            logger.info("<<<<<--- merchId为：" + bizTransactionAmountEntity.getMerchId() + "时，该人员所属的机构流水表为：" + tableName + "。 --->>>>> -");
            bizTransactionAmountEntity.setTableName(tableName);
            // 将该id的数据添加到交易通知表内
//            logger.info("<<<<<--- 将merchId为：" + bizTransactionAmountEntity.getMerchId() + "的数据添加到交易通知表内 --->>>>> -");
            transactionMapper.insert(bizTransactionAmountEntity);
            SimpleDateFormat dateDf = new SimpleDateFormat("yyyy-MM-dd");
            String dateTime = dateDf.format(bizTransactionAmountEntity.getHostDate());
            // 查询交易类型
//            logger.info("<<<<<--- 通过merchId为：" + bizTransactionAmountEntity.getMerchId() + "的数据查询交易类型 --->>>>> -");
            int type = transactionMapper.serlectType(bizTransactionAmountEntity.getEnterMode());
            if (map.get(bizTransactionAmountEntity.getMerchId() + "_" + dateTime) != null) {
                btsr = map.get(bizTransactionAmountEntity.getMerchId() + "_" + dateTime);
                btsr.setCurrentLevel(btsr.getCurrentLevel() + bizTransactionAmountEntity.getAmnount());
                btsr.setAllMoney(btsr.getAllMoney() + bizTransactionAmountEntity.getAmnount());
                // type = 1 为刷卡
                if (type == 1) {
                    btsr.setCurrentLevelPayCard(btsr.getCurrentLevelPayCard() + bizTransactionAmountEntity.getAmnount());
                    // type = 2 为扫码
                } else if (type == 2) {
                    btsr.setCurrentLevelScanCode(btsr.getCurrentLevelScanCode() + bizTransactionAmountEntity.getAmnount());
                    // type = 9 为其他
                } else if (type == 9) {
                    btsr.setCurrentLevelOther(btsr.getCurrentLevelOther() + bizTransactionAmountEntity.getAmnount());
                }
                btsr.setHostDate(dateTime);
//                logger.info("<<<<<--- 然后讲key值为：" + bizTransactionAmountEntity.getMerchId() + "_" + dateTime + " value为：" + btsr + "再放入map内 --->>>>> -");
                map.put(bizTransactionAmountEntity.getMerchId() + "_" + dateTime, btsr);
            } else {
                btsr.setMerchId(bizTransactionAmountEntity.getMerchId());
                btsr.setCurrentLevel(bizTransactionAmountEntity.getAmnount());
                btsr.setAllMoney(bizTransactionAmountEntity.getAmnount());
                // type = 1 为刷卡
                if (type == 1) {
                    btsr.setCurrentLevelPayCard(bizTransactionAmountEntity.getAmnount());
                    // type = 2 为扫码
                } else if (type == 2) {
                    btsr.setCurrentLevelScanCode(bizTransactionAmountEntity.getAmnount());
                    // type = 9 为其他
                } else if (type == 9) {
                    btsr.setCurrentLevelOther(bizTransactionAmountEntity.getAmnount());
                }
                btsr.setHostDate(dateTime);
//                logger.info("<<<<<--- 然后讲key值为：" + bizTransactionAmountEntity.getMerchId() + "_" + dateTime + " value为：" + btsr + "再放入map内 --->>>>> -");
                map.put(bizTransactionAmountEntity.getMerchId() + "_" + dateTime, btsr);
            }
            // 查询本级的上级
//            logger.info("<<<<<--- 通过merchId为：" + bizTransactionAmountEntity.getMerchId() + "的数据查询本级的上级 --->>>>> -");
            List<BizMerchParentRelateds> parentList = transactionMapper.selectParentId(bizTransactionAmountEntity.getMerchId());
//            logger.info("<<<<<--- 调用查询本级的上级的方法 --->>>>> -");
            map = this.handleData(parentList, map, btsr, bizTransactionAmountEntity, type);
        }
//        logger.info("<<<<<--- 往map内放值的方法最终返回map为：" + map + " --->>>>> -");
        return map;
    }

    /**
     * @author: haoran
     * @date: 2022/7/21
     * 方法名称： 查询本级的上级
     */
    public Map<String, BizTransactionStatisticsRecord> handleData(List<BizMerchParentRelateds> parentList, Map<String, BizTransactionStatisticsRecord> map, BizTransactionStatisticsRecord btsr, BizTransactionAmountEntity bizTransactionAmountEntity, int type) {
//        logger.info("<<<<<--- 查询本级的上级时，接收到的List为：" + parentList + " --->>>>> -");
//        logger.info("<<<<<--- 查询本级的上级时，接收到的map为：" + map + " --->>>>> -");
//        logger.info("<<<<<--- 查询本级的上级时，接收到的实体对象BizTransactionAmountEntity为：" + bizTransactionAmountEntity + " --->>>>> -");
        for (BizMerchParentRelateds parent : parentList) {
            btsr = new BizTransactionStatisticsRecord();
            SimpleDateFormat dateDf = new SimpleDateFormat("yyyy-MM-dd");
            String dateTime = dateDf.format(bizTransactionAmountEntity.getHostDate());
            if (map.get(parent.getParentId() + "_" + dateTime) != null) {
                btsr = map.get(parent.getParentId() + "_" + dateTime);
                btsr.setLowerLevel(btsr.getLowerLevel() + bizTransactionAmountEntity.getAmnount());
                btsr.setAllMoney(btsr.getAllMoney() + bizTransactionAmountEntity.getAmnount());
                // type = 1 为刷卡
                if (type == 1) {
                    btsr.setLowerLevelPayCard(btsr.getLowerLevelPayCard() + bizTransactionAmountEntity.getAmnount());
                } else if (type == 2) {
                    btsr.setLowerLevelScanCode(btsr.getLowerLevelScanCode() + bizTransactionAmountEntity.getAmnount());
                } else if (type == 9) {
                    btsr.setLowerLevelOther(btsr.getLowerLevelOther() + bizTransactionAmountEntity.getAmnount());
                }
                btsr.setHostDate(dateTime);
//                logger.info("<<<<<--- 然后讲key值为：" + parent.getParentId() + "_" + btsr.getHostDate() + " value为：" + btsr + "再放入map内 --->>>>> -");
                map.put(parent.getParentId() + "_" + btsr.getHostDate(), btsr);
            } else {
                btsr.setMerchId(parent.getParentId());
                btsr.setLowerLevel(bizTransactionAmountEntity.getAmnount());
                btsr.setAllMoney(bizTransactionAmountEntity.getAmnount());
                // type = 1 为刷卡
                if (type == 1) {
                    btsr.setLowerLevelPayCard(bizTransactionAmountEntity.getAmnount());
                } else if (type == 2) {
                    btsr.setLowerLevelScanCode(bizTransactionAmountEntity.getAmnount());
                } else if (type == 9) {
                    btsr.setLowerLevelOther(bizTransactionAmountEntity.getAmnount());
                }
                btsr.setHostDate(dateTime);
//                logger.info("<<<<<--- 然后讲key值为：" + parent.getParentId() + "_" + btsr.getHostDate() + " value为：" + btsr + "再放入map内 --->>>>> -");
                map.put(parent.getParentId() + "_" + dateTime, btsr);
            }
        }
//        logger.info("<<<<<--- 查询本级的上级方法的最终返回map为：" + map + " --->>>>> -");
        return map;
    }

    /**
     * @author: haoran
     * @date: 2022/7/21
     * 方法名称： 处理数据库数据
     */
    public void processingData(Map<String, BizTransactionStatisticsRecord> map,BizTransactionStatisticsRecord btsr ) throws ParseException {
//        logger.info("<<<<<--- 处理数据库数据时，接收到的map为：" + map + " --->>>>> -");
        for (String key : map.keySet()) {
            // 日
//            logger.info("<<<<<--- 处理类型为“日”数据 --->>>>> -");
            map.get(key).setTimeType(0);
            map.get(key).setDateTime(map.get(key).getHostDate());
//            logger.info("<<<<<--- 通过key值为：" + key + "的数据去查询该数据是否已经存在 --->>>>> -");
            try{
                transactionMapper.selectTransactionByInnerMerchCode(map.get(key));
            }catch (Exception e){
                System.out.println("------------------------------------------------");
                System.out.println(map.get(key).toString());
            }

            btsr = transactionMapper.selectTransactionByInnerMerchCode(map.get(key));
            if (btsr == null) {
//                logger.info("<<<<<--- key值为：" + key + "的数据为：" + map.get(key) + " --->>>>> -");
                transactionMapper.inssertTransactionByInnerMerchCode(map.get(key));
            } else {
//                btsr.setCurrentLevel(map.get(key).getCurrentLevel() + btsr.getCurrentLevel());
//                btsr.setLowerLevel(map.get(key).getLowerLevel() + btsr.getLowerLevel());
//                btsr.setCurrentLevelPayCard(map.get(key).getCurrentLevelPayCard() + btsr.getCurrentLevelPayCard());
//                btsr.setLowerLevelPayCard(map.get(key).getLowerLevelPayCard() + btsr.getLowerLevelPayCard());
//                btsr.setCurrentLevelScanCode(map.get(key).getCurrentLevelScanCode() + btsr.getCurrentLevelScanCode());
//                btsr.setLowerLevelScanCode(map.get(key).getLowerLevelScanCode() + btsr.getLowerLevelScanCode());
//                btsr.setCurrentLevelOther(map.get(key).getCurrentLevelOther() + btsr.getCurrentLevelOther());
//                btsr.setLowerLevelOther(map.get(key).getLowerLevelOther() + btsr.getLowerLevelOther());
//                btsr.setAllMoney(map.get(key).getAllMoney() + btsr.getAllMoney());
                btsr.setCurrentLevel(map.get(key).getCurrentLevel());
                btsr.setLowerLevel(map.get(key).getLowerLevel());
                btsr.setCurrentLevelPayCard(map.get(key).getCurrentLevelPayCard());
                btsr.setLowerLevelPayCard(map.get(key).getLowerLevelPayCard());
                btsr.setCurrentLevelScanCode(map.get(key).getCurrentLevelScanCode());
                btsr.setLowerLevelScanCode(map.get(key).getLowerLevelScanCode());
                btsr.setCurrentLevelOther(map.get(key).getCurrentLevelOther());
                btsr.setLowerLevelOther(map.get(key).getLowerLevelOther());
                btsr.setAllMoney(map.get(key).getAllMoney());
//                logger.info("<<<<<--- 最终key值为：" + key + "的数据为：" + map.get(key) + " --->>>>> -");
                transactionMapper.updateTransactionByInnerMerchCode(btsr);
            }
            // 月
//            logger.info("<<<<<--- 处理类型为“月”数据 --->>>>> -");
            SimpleDateFormat monthDf = new SimpleDateFormat("yyyy-MM");
            String monthTime = monthDf.format(monthDf.parse(map.get(key).getHostDate()));
            map.get(key).setTimeType(1);
            map.get(key).setDateTime(monthTime);
//            logger.info("<<<<<--- 通过key值为：" + key + "的数据去查询该数据是否已经存在 --->>>>> -");
            btsr = transactionMapper.selectTransactionByInnerMerchCode(map.get(key));
            if (btsr == null) {
//                logger.info("<<<<<--- key值为：" + key + "的数据为：" + map.get(key) + " --->>>>> -");
                transactionMapper.inssertTransactionByInnerMerchCode(map.get(key));
            } else {
//                btsr.setCurrentLevel(map.get(key).getCurrentLevel() + btsr.getCurrentLevel());
//                btsr.setLowerLevel(map.get(key).getLowerLevel() + btsr.getLowerLevel());
//                btsr.setCurrentLevelPayCard(map.get(key).getCurrentLevelPayCard() + btsr.getCurrentLevelPayCard());
//                btsr.setLowerLevelPayCard(map.get(key).getLowerLevelPayCard() + btsr.getLowerLevelPayCard());
//                btsr.setCurrentLevelScanCode(map.get(key).getCurrentLevelScanCode() + btsr.getCurrentLevelScanCode());
//                btsr.setLowerLevelScanCode(map.get(key).getLowerLevelScanCode() + btsr.getLowerLevelScanCode());
//                btsr.setCurrentLevelOther(map.get(key).getCurrentLevelOther() + btsr.getCurrentLevelOther());
//                btsr.setLowerLevelOther(map.get(key).getLowerLevelOther() + btsr.getLowerLevelOther());
//                btsr.setAllMoney(map.get(key).getAllMoney() + btsr.getAllMoney());
                btsr.setCurrentLevel(map.get(key).getCurrentLevel());
                btsr.setLowerLevel(map.get(key).getLowerLevel());
                btsr.setCurrentLevelPayCard(map.get(key).getCurrentLevelPayCard());
                btsr.setLowerLevelPayCard(map.get(key).getLowerLevelPayCard());
                btsr.setCurrentLevelScanCode(map.get(key).getCurrentLevelScanCode());
                btsr.setLowerLevelScanCode(map.get(key).getLowerLevelScanCode());
                btsr.setCurrentLevelOther(map.get(key).getCurrentLevelOther());
                btsr.setLowerLevelOther(map.get(key).getLowerLevelOther());
                btsr.setAllMoney(map.get(key).getAllMoney());
//                logger.info("<<<<<--- 最终key值为：" + key + "的数据为：" + map.get(key) + " --->>>>> -");
                transactionMapper.updateTransactionByInnerMerchCode(btsr);
            }
            // 年
//            logger.info("<<<<<--- 处理类型为“年”数据 --->>>>> -");
            SimpleDateFormat yearDf = new SimpleDateFormat("yyyy");
            String yearTime = yearDf.format(monthDf.parse(map.get(key).getHostDate()));
            map.get(key).setTimeType(2);
            map.get(key).setDateTime(yearTime);
//            logger.info("<<<<<--- 通过key值为：" + key + "的数据去查询该数据是否已经存在 --->>>>> -");
            btsr = transactionMapper.selectTransactionByInnerMerchCode(map.get(key));
            if (btsr == null) {
//                logger.info("<<<<<--- key值为：" + key + "的数据为：" + map.get(key) + " --->>>>> -");
                transactionMapper.inssertTransactionByInnerMerchCode(map.get(key));
            } else {
//                btsr.setCurrentLevel(map.get(key).getCurrentLevel() + btsr.getCurrentLevel());
//                btsr.setLowerLevel(map.get(key).getLowerLevel() + btsr.getLowerLevel());
//                btsr.setCurrentLevelPayCard(map.get(key).getCurrentLevelPayCard() + btsr.getCurrentLevelPayCard());
//                btsr.setLowerLevelPayCard(map.get(key).getLowerLevelPayCard() + btsr.getLowerLevelPayCard());
//                btsr.setCurrentLevelScanCode(map.get(key).getCurrentLevelScanCode() + btsr.getCurrentLevelScanCode());
//                btsr.setLowerLevelScanCode(map.get(key).getLowerLevelScanCode() + btsr.getLowerLevelScanCode());
//                btsr.setCurrentLevelOther(map.get(key).getCurrentLevelOther() + btsr.getCurrentLevelOther());
//                btsr.setLowerLevelOther(map.get(key).getLowerLevelOther() + btsr.getLowerLevelOther());
//                btsr.setAllMoney(map.get(key).getAllMoney() + btsr.getAllMoney());
                btsr.setCurrentLevel(map.get(key).getCurrentLevel());
                btsr.setLowerLevel(map.get(key).getLowerLevel());
                btsr.setCurrentLevelPayCard(map.get(key).getCurrentLevelPayCard());
                btsr.setLowerLevelPayCard(map.get(key).getLowerLevelPayCard());
                btsr.setCurrentLevelScanCode(map.get(key).getCurrentLevelScanCode());
                btsr.setLowerLevelScanCode(map.get(key).getLowerLevelScanCode());
                btsr.setCurrentLevelOther(map.get(key).getCurrentLevelOther());
                btsr.setLowerLevelOther(map.get(key).getLowerLevelOther());
                btsr.setAllMoney(map.get(key).getAllMoney());
//                logger.info("<<<<<--- 最终key值为：" + key + "的数据为：" + map.get(key) + " --->>>>> -");
                transactionMapper.updateTransactionByInnerMerchCode(btsr);
            }
        }
    }
}
